# import schedule
# import time
# import subprocess
# import json
# import logging
# from datetime import datetime
# import os
#
# # 配置日志
# logging.basicConfig(
#     level=logging.INFO,
#     format='%(asctime)s - %(levelname)s - %(message)s',
#     handlers=[
#         logging.FileHandler('E:\\test\\newproject\\scheduler.log'),
#         logging.StreamHandler()
#     ]
# )
#
#
# class TaskScheduler:
#     def __init__(self, config_file):
#         self.config_file = config_file
#         self.tasks = self.load_config()
#
#     def load_config(self):
#         """加载任务配置"""
#         try:
#             with open(self.config_file, 'r', encoding='utf-8') as f:
#                 return json.load(f)['tasks']
#         except Exception as e:
#             logging.error(f"加载配置文件失败: {e}")
#             return []
#
#     def run_script(self, script_path, task_name):
#         """运行Python脚本"""
#         try:
#             logging.info(f"开始执行任务: {task_name}")
#
#             # 使用subprocess运行脚本
#             result = subprocess.run(
#                 ['python', script_path],
#                 capture_output=True,
#                 text=True,
#                 timeout=300  # 5分钟超时
#             )
#
#             if result.returncode == 0:
#                 logging.info(f"任务完成: {task_name}")
#                 if result.stdout:
#                     logging.info(f"输出: {result.stdout.strip()}")
#             else:
#                 logging.error(f"任务失败: {task_name}")
#                 logging.error(f"错误: {result.stderr.strip()}")
#
#         except subprocess.TimeoutExpired:
#             logging.error(f"任务超时: {task_name}")
#         except Exception as e:
#             logging.error(f"执行任务异常 {task_name}: {e}")
#
#     def setup_schedule(self):
#         """设置定时任务"""
#         for task in self.tasks:
#             if not task['enabled']:
#                 continue
#
#             script_path = task['script_path']
#             task_name = task['name']
#             schedule_time = task['schedule']
#
#             # 每天固定时间执行
#             schedule.every().day.at(schedule_time).do(
#                 self.run_script, script_path, task_name
#             )
#
#             logging.info(f"已安排任务: {task_name} - 每天 {schedule_time}")
#
#     def run(self):
#         """运行调度器"""
#         logging.info("任务调度器启动...")
#         self.setup_schedule()
#
#         # 立即执行一次所有任务（可选）
#         # for task in self.tasks:
#         #     if task['enabled']:
#         #         self.run_script(task['script_path'], task['name'])
#
#         while True:
#             try:
#                 schedule.run_pending()
#                 time.sleep(60)  # 每分钟检查一次
#             except KeyboardInterrupt:
#                 logging.info("调度器被用户中断")
#                 break
#             except Exception as e:
#                 logging.error(f"调度器运行异常: {e}")
#                 time.sleep(60)
#
#
# if __name__ == "__main__":
#     # scheduler = TaskScheduler("C:\\scripts\\task_config.json")E:\test\newproject\
#     scheduler = TaskScheduler("E:\\test\\newproject\\task_config.json")
#     scheduler.run()
from concurrent.futures import ThreadPoolExecutor

import schedule
import time
import os
import logging
from datetime import datetime

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('scheduler.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)


def run_script_simple(script_path, task_name):
    """简化版脚本运行函数"""
    try:
        logging.info(f"开始执行: {task_name}")

        # 使用os.system替代subprocess，避免编码问题
        command = f'python "{script_path}"'
        return_code = os.system(command)

        if return_code == 0:
            logging.info(f"任务完成: {task_name}")
        else:
            logging.error(f"任务失败: {task_name}, 返回码: {return_code}")

    except Exception as e:
        logging.error(f"执行异常 {task_name}: {str(e)}")


# 任务配置
TASKS = [
    {"name": "发送邮件", "script": r"C:\scripts\send_mail.py", "time": "14:16"},
]

# 设置定时任务
for task in TASKS:
    if os.path.exists(task["script"]):
        schedule.every().day.at(task["time"]).do(run_script_simple, task["script"], task["name"])
        logging.info(f"已安排: {task['name']} - {task['time']}")
    else:
        logging.error(f"脚本不存在: {task['script']}")

# 运行调度器
while True:
    schedule.run_pending()
    time.sleep(30)